﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

using SPaDevToolkit.Administration;

namespace Northwind.ServiceObjects
{
    internal class NorthwindDatabaseManager : SPaDatabaseManager<NorthwindApplication, NorthwindService>
    {
        #region Overrides
        public override DBT CreateDatabase<DBT>(SPDatabaseParameters parameters)
        {
            string error;

            if (! IsDatabaseValid(parameters.Database, parameters.Server, out error))
            {
                throw new SPException(error);
            }

            if (typeof(DBT).Equals(typeof(NorthwindDatabase)))
            {
                NorthwindDatabase database = CreateOrAttachDatabase(parameters);
                return database as DBT;
            }
            else
                throw new ArgumentException("Cannot create an application database of type " + typeof(DBT).ToString());
        }

        private static NorthwindDatabase CreateOrAttachDatabase(SPDatabaseParameters databaseParameters)
        {
            SPDatabaseServiceInstance serviceInstance = databaseParameters.EnsureServiceInstance();
            NorthwindDatabase database = new NorthwindDatabase(databaseParameters.Database, serviceInstance);
            database.Username = databaseParameters.Username;
            database.Password = databaseParameters.Password;

            database.NeedsUpgrade = true;

            if (database.Exists)
            {
                database.Update(true);
                return database;
            }

            database.Update();
            return database;
        }

        #endregion
    }
}
